/* 
 * File:   RoutingTable.cpp
 * Author: henrya
 * 
 * Created on June 26, 2009, 6:54 PM
 */

#include "RoutingTable.h"
#include "RuntimeException.h"
#include <limits>
#include <iostream>
using std::numeric_limits;
using std::cout;
using std::endl;

RoutingTable::RoutingTable(int nodeId, vector<int>& allNodes) : nodeId(nodeId), allNodes(allNodes) {
    distance = new int[allNodes.size()];
    if (distance == NULL) {
        RuntimeException ex("RoutingTable - Could not allocate memory for sitance vector");
        throw ex;
    }
    bool valid(false);
    int maxInt = numeric_limits<int>::max();
    for (unsigned int i = 0; i < allNodes.size(); i++) {
        if (indexOf(nodeId) == i) {
            distance[i] = 0;
            valid = true;
        } else {
            distance[i] = maxInt;
        }
    }
    if (!valid) {
        RuntimeException ex("RoutingTable - nodeId not in allNodes vector!");
        throw ex;
    }
    nextNode = new int[allNodes.size()];
    if (nextNode == NULL) {
        RuntimeException ex("RoutingTable - Could not allocate memory for next node vector");
        throw ex;
    }
    for (unsigned int i = 0; i < allNodes.size(); i++) {
        if (indexOf(nodeId) == i) {
            nextNode[i] = i;
        } else {
            nextNode[i] = -1;
        }

    }
}

RoutingTable::~RoutingTable() {
    delete distance;
    delete nextNode;
}

void RoutingTable::update(RoutingTable& table) {
    for (unsigned int i = 0; i < allNodes.size(); i++) {
        if (distance[i] > table.distance[i]) {
            distance[i] = 1 + table.distance[i];
            nextNode[i] = indexOf(table.getId());
        }
    }
}

unsigned int RoutingTable::indexOf(int nodeNumber) {
    for (unsigned int i = 0; i < allNodes.size(); i++) {
        if (nodeNumber == allNodes.at(i)) {
            return i;
        }
    }
    return -1;
}

int RoutingTable::getId() {
    return nodeId;
}

void RoutingTable::printRT(){
  vector<int>::iterator it;
  cout<<"printing routing table:"<<endl;
  for( it = allNodes.begin(); it != allNodes.end(); it++ ) {
      cout<<"\t"<<*it;
  }
}

//int main() {
//    vector<int> nodes;
//    nodes.push_back(2);
//    nodes.push_back(0);
//    nodes.push_back(3);
//    nodes.push_back(4);
//    RoutingTable table(2, nodes);
//    RoutingTable table2(0, nodes);
//    table.update(table2);
//    int i = 0;
//    cout << i<<endl;
//
//    cout<<"barak added testing"<<endl;
//    table.printRT();
//}
